import { getById, get, inc, count, add, remove } from "../../utils/db";
Page({
  data: {
    detail: null,      //商品详情
    isLike: false,     //true已经关注；false 没有关注
    tag: true,     //true 按钮可以点击；false 按钮不可以点击
  },
  async onLoad(e) {
    //菜谱id
    let id = e.id;
    //访问量自增
    let res = await inc({ collection: "menu", id: id, count: 1, field: "views" }).catch(err => {
      console.log(err)
    })


    //获取菜谱详情
    let result = await getById({ collection: "menu", id: id }).catch(err => {
      console.error(err)
    })

    //实现列表页中相应数据的views累加
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit("myInc", { id: id })

    //修改导航栏标题
    wx.setNavigationBarTitle({
      title: result.data.name,
    })

    //渲染到页面
    this.setData({
      detail: result.data
    })


    //判断是否关注
    let openid = wx.getStorageSync('openid')
    let num = await count({ collection: "likes", where: { _openid: openid, menuid: id } }).catch(err => {
      console.error(err)
    })
    // console.log(num)
    if (num.total == 0) {
      //没有关注
      this.setData({
        isLike: false
      })
    } else {
      //已经关注
      this.setData({
        isLike: true
      })
    }

  },
  //点击放大图片
  preview(e) {
    //获取当前图片链接
    let url = e.currentTarget.dataset.url;
    //全屏播放
    wx.previewImage({
      urls: this.data.detail.image,
      current: url
    })
  },
  //点击进行关注
  async addLike() {
    if (!this.data.tag) return;     //检查门是否关闭，如果关闭，就不进行后面的逻辑
    this.data.tag = false;          //先关门

    //likes集合中添加记录
    let result = await add({
      collection: "likes", data: {
        menuid: this.data.detail._id
      }
    }).catch(err => console.error(err))


    //menu中的likes字段+1
    let res = await inc({ collection: "menu", id: this.data.detail._id, field: "likes" }).catch(err => {
      console.error(err)
    })
    //页面中关注数量累加
    this.data.detail.likes++;
    this.setData({
      detail: this.data.detail,
      isLike: true
    })

    this.data.tag = true;     //把门打开
  },
  //取消关注
  async cancelLike() {
    if (!this.data.tag) return;     //检查门是否关闭，如果关闭，就不进行后面的逻辑
    this.data.tag = false;          //先关门
    //删除likes中的记录（openid和menuid）
    let openid = wx.getStorageSync('openid');   //用户的openid
    let menuid = this.data.detail._id;      //菜谱id

    //删除likes中记录
    let result = await remove({ collection: "likes", where: { _openid: openid, menuid } }).catch(err => {
      console.log(err)
    })
    //menu集合中likes字段-1

    await inc({ collection: "menu", id: menuid, count: -1, field: "likes" }).catch(err => {
      console.error(err)
    })
    //页面中的likes-1
    this.data.detail.likes--;
    this.setData({
      detail: this.data.detail,
      isLike: false
    })

    this.data.tag = true;     //把门打开
  }

})